package com.jt.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.ManagerMapper;
import com.jt.pojo.Manager;
import com.jt.service.ManagerService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class ManagerServiceImpl implements ManagerService {
	@Autowired
	private ManagerMapper managerMapper;
	
	/**
	 * 业务逻辑：
	 * 1.根据用户名用户是否存在
	 * 2.不存在，插入：密码采用MD5加密
	 * 3.存在，提示错误信息
	 */
	@Override
	public SysResult saveManager(Manager manager) {
		QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", manager.getUsername());
		Manager selectOne = managerMapper.selectOne(queryWrapper);
		if(selectOne != null ) {    //用户名存在，提示错误信息
			return SysResult.fail("用户名已存在");
		}else {            //用户名不存在，进行插入
			//md5加密
		    String md5Password = DigestUtils.md5DigestAsHex(manager.getPassword().getBytes());
			manager.setPassword(md5Password)
				   .setCreated(new Date())
				   .setUpdated(manager.getCreated());
			managerMapper.insert(manager);
			return SysResult.success();
		}
	}
	/**
	 * 业务逻辑：
	 * 1.根据username  password 判断用户是否存在
	 * 2.存在，返回成功，保存到缓存
	 * 3.不存在，返回失败
	 */
	@Override
	public SysResult findByUP(Manager manager) {
		//加密
		String md5Password = DigestUtils.md5DigestAsHex(manager.getPassword().getBytes());
		manager.setPassword(md5Password);
		
		QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>(manager);
		Manager selectOne = managerMapper.selectOne(queryWrapper);
		if(selectOne != null) {  //存在，返回成功	
			return SysResult.success("欢迎"+selectOne.getUsername(),selectOne);
		}else {			
			return SysResult.fail("用户名或密码错误！");
		}

	}
	
	/**
	 * 修改密码：
	 * 1.判断旧密码是否正确
	 * 2.正确：更改为新密码
	 * 3.不正确：提示旧密码错误
	 */
	@Override
	public SysResult matchAndUpdate(Long id, String password, String newPassword) {
		//加密
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		//查询
		Manager selectById = managerMapper.selectById(id);
		//判断旧密码是否正确
		if(selectById.getPassword().equals(md5Password)) {  //正确
			String md5NewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
			Manager manager = new Manager();
			manager.setId(id).setPassword(md5NewPassword);
			managerMapper.updateById(manager);
			return SysResult.success();
		}
		return SysResult.fail("旧密码不正确！");
	}
	
}
